<#
.SYNOPSIS
    一键启动 Next.js 生产服务器的 PowerShell 脚本

.DESCRIPTION
    此脚本会自动检查并安装必要的软件（Node.js 和 pnpm）
    然后安装项目依赖，构建项目并启动 Next.js 生产服务器。

.NOTES
    文件名: Start-NextJS-Production-CN.ps1
    作者: 你的名字
    创建日期: $(Get-Date -Format "yyyy-MM-dd")
#>

# 设置执行策略（仅在首次运行时需要）
function Set-ExecutionPolicyIfNeeded {
    $currentPolicy = Get-ExecutionPolicy -Scope CurrentUser
    if ($currentPolicy -ne "RemoteSigned" -and $currentPolicy -ne "Unrestricted") {
        Write-Host "正在设置执行策略为 RemoteSigned..." -ForegroundColor Yellow
        Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
    }
}

# 检查并安装 Node.js
function Install-NodeJS {
    # 检查是否已安装 Node.js
    $nodeInstalled = $false
    try {
        $nodeVersion = node -v 2>$null
        if ($nodeVersion) {
            Write-Host "已安装 Node.js 版本: $nodeVersion" -ForegroundColor Green
            $nodeInstalled = $true
            return
        }
    } catch {}

    Write-Host "未检测到 Node.js，正在安装..." -ForegroundColor Yellow
    
    # 下载 Node.js
    $nodeInstallerUrl = "https://npmmirror.com/mirrors/node/v20.11.0/node-v20.11.0-x64.msi"
    $installerPath = "$env:TEMP\nodejs-installer.msi"
    
    try {
        # 下载安装程序
        Write-Host "正在下载 Node.js 安装程序..." -ForegroundColor Cyan
        Invoke-WebRequest -Uri $nodeInstallerUrl -OutFile $installerPath
        
        # 静默安装 Node.js
        Write-Host "正在安装 Node.js，这可能需要几分钟..." -ForegroundColor Cyan
        Start-Process -FilePath "msiexec.exe" -ArgumentList "/i", "$installerPath", "/qn", "ADDLOCAL=ALL" -Wait
        
        # 刷新环境变量
        $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
        
        # 验证安装
        $nodeVersion = node -v
        Write-Host "Node.js 安装成功! 版本: $nodeVersion" -ForegroundColor Green
        
        # 配置 npm
        Write-Host "正在配置 npm ..." -ForegroundColor Cyan
        npm config set registry https://registry.npmmirror.com
        npm config set disturl https://npmmirror.com/dist
        npm config set cache "$env:USERPROFILE\.npm-taobao-cache"
        Write-Host "npm 已配置" -ForegroundColor Green
    } catch {
        Write-Host "安装 Node.js 时出错: $_" -ForegroundColor Red
        exit 1
    } finally {
        # 清理安装文件
        if (Test-Path $installerPath) {
            Remove-Item $installerPath -Force
        }
    }
}

# 检查并安装 pnpm
function Install-Pnpm {
    # 检查是否已安装 pnpm
    $pnpmInstalled = $false
    try {
        $pnpmVersion = pnpm -v 2>$null
        if ($pnpmVersion) {
            Write-Host "已安装 pnpm 版本: $pnpmVersion" -ForegroundColor Green
            $pnpmInstalled = $true
        }
    } catch {}

    if (-not $pnpmInstalled) {
        Write-Host "未检测到 pnpm，正在安装..." -ForegroundColor Yellow
        
        try {
            # 使用 npm 安装 pnpm
            Write-Host "正在通过 npm 安装 pnpm..." -ForegroundColor Cyan
            npm install -g pnpm --registry=https://registry.npmmirror.com
            
            # 配置 pnpm
            Write-Host "正在配置 pnpm ..." -ForegroundColor Cyan
            pnpm config set registry https://registry.npmmirror.com
            pnpm config set store-dir "$env:USERPROFILE\.pnpm-store-taobao"
            
            # 验证安装
            $pnpmVersion = pnpm -v
            Write-Host "pnpm 安装成功! 版本: $pnpmVersion" -ForegroundColor Green
            Write-Host "pnpm 已配置" -ForegroundColor Green
        } catch {
            Write-Host "安装 pnpm 时出错: $_" -ForegroundColor Red
            exit 1
        }
    }
}

# 安装项目依赖、构建并启动生产服务器
function Start-NextJSProduction {
    # 安装依赖
    Write-Host "正在安装项目依赖 (pnpm install)..." -ForegroundColor Cyan
    pnpm install --registry=https://registry.npmmirror.com
    
    if ($LASTEXITCODE -ne 0) {
        Write-Host "安装依赖时出错，请检查网络连接或项目配置。" -ForegroundColor Red
        exit 1
    }
    
    # 构建项目
    Write-Host "正在构建项目 (pnpm run build)..." -ForegroundColor Cyan
    pnpm run build
    
    if ($LASTEXITCODE -ne 0) {
        Write-Host "构建项目时出错，请检查项目配置。" -ForegroundColor Red
        exit 1
    }
    
    # 启动生产服务器
    Write-Host "构建完成，正在启动生产服务器 (pnpm run start)..." -ForegroundColor Cyan
    Write-Host "----------------------------------------" -ForegroundColor Green
    Write-Host "Next.js 生产服务器即将启动..." -ForegroundColor Green
    Write-Host "启动完成后，可以在浏览器中访问: http://localhost:3000" -ForegroundColor Green
    Write-Host "按 Ctrl+C 可以停止服务器" -ForegroundColor Green
    Write-Host "----------------------------------------" -ForegroundColor Green
    
    pnpm run start
}

# 主程序
function Main {
    # 设置窗口标题
    $Host.UI.RawUI.WindowTitle = "Next.js 生产服务器一键启动工具"
    
    # 设置执行策略
    Set-ExecutionPolicyIfNeeded
    
    # 显示欢迎信息
    Write-Host "`nNext.js 生产服务器一键启动工具`n" -ForegroundColor Magenta
    Write-Host "此脚本将自动:" -ForegroundColor Cyan
    Write-Host "1. 检查并安装 Node.js (如果未安装)" -ForegroundColor Cyan
    Write-Host "2. 检查并安装 pnpm (如果未安装)" -ForegroundColor Cyan
    Write-Host "3. 安装项目依赖 (pnpm install)" -ForegroundColor Cyan
    Write-Host "4. 构建项目 (pnpm run build)" -ForegroundColor Cyan
    Write-Host "5. 启动生产服务器 (pnpm run start)`n" -ForegroundColor Cyan
    
    # 检查并安装必要软件
    Install-NodeJS
    Install-Pnpm
    
    # 启动项目
    Start-NextJSProduction
}

# 执行主程序
Main